package com.orange.fastdfsjava.controller;

import com.orange.fastdfsjava.pojo.Admin;
import com.orange.fastdfsjava.service.AdminService;
import com.orange.fastdfsjava.utils.AuthContextHolder;
import com.orange.fastdfsjava.utils.JwtHelper;
import com.orange.fastdfsjava.utils.R;
import com.orange.fastdfsjava.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 管理员表
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/admins")
public class AdminController {

    @Resource
    private AdminService adminService;

    //管理员进行用户名密码登录
    @PostMapping("{name}/{password}")
    public R loginAdmin(@PathVariable String name, @PathVariable String password) {
        log.info("管理员进行用户名:===>{},密码登录:===>{}", name, password);
        int count = adminService.selectCountAdminLogin(name, password);
        if (count > 0) {
            Admin admin = adminService.selectAdminLogin(name, password);
            String adminName = admin.getName();
            String roleName = admin.getRoleName();
            if (StringUtils.isNotBlank(adminName)) {
                String token = JwtHelper.createToken(admin.getId(), admin.getName());

                return R.ok().setMessage("success").setCode(200).data("adminName", adminName).data("roleName", roleName).data("token", token);
            }
        }
        return R.error().setMessage("fail");
    }

    //根据id查询管理员
    @GetMapping()
    public R getAdminById(HttpServletRequest request) {
        Integer adminId = AuthContextHolder.getAdminId(request);
        Admin admin = adminService.getAdminById(adminId);
        log.info("根据id查询管理员:===>{}", admin);
        return R.ok().setMessage("success").setCode(200).data("admin", admin);
    }

}